package com.github.common.extend.demo.util.excel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.github.common.extend.demo.config.json.ValueFormat;
import org.apache.commons.lang.StringUtils;
import java.text.MessageFormat;
import java.util.regex.Pattern;

/**
 * @author wangjj7
 * @date 2023/3/13
 * @description
 */
public class ValueFormatConverter implements Converter<Object> {

    @Override
    public Class supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Object convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return cellData.getStringValue();
    }

    @Override
    public WriteCellData convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null){
            return new WriteCellData<>("");
        }
        ValueFormat valueFormatAnnotation = contentProperty.getField().getAnnotation(ValueFormat.class);
        if (valueFormatAnnotation != null){
            String str = value.toString();
            String patternStr = valueFormatAnnotation.pattern();
            boolean match = StringUtils.isEmpty(patternStr) ? true : Pattern.compile(patternStr).matcher(str).matches();
            if (match){
                String serializeValue = valueFormatAnnotation.writeValue();
                if (StringUtils.isNotEmpty(serializeValue)){
                    String writeValueStr = MessageFormat.format(serializeValue ,value);
                    return new WriteCellData(writeValueStr);
                }
            }
        }
        return new WriteCellData("");
    }
}
